<?php

/*
采购订单列表
*/
namespace Modules\Intelligent\Http\Repositories;


use App\Services\UnitService;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Http\Request;
use Modules\Base\Models\Material;
use Modules\Base\Repository\BoxNumberRepository;
use Modules\Purchasing\Models\Provisional;
use Modules\Purchasing\Models\Provisionalschedule;
use Illuminate\Support\Facades\DB;
use Catch\Exceptions\FailedException;
use Modules\Base\Service\BoxService;
use Modules\Purchasing\Models\Supplier;
use Modules\Purchasing\Models\Supplierschedule;
use Modules\Purchasing\Models\Purchaseorder;
use Modules\Purchasing\Models\Purchaseorderschedule;
use Modules\Warehouse\Models\Stash;use Modules\Warehouse\Models\Storagelocation;
use Modules\Purchasing\Models\Inspectionlist;
use Modules\Purchasing\Models\Inspectionlistcheck;
use extend\services\warehouse\{warehouseService};//引入自定义类
use Modules\Intelligent\Http\Repositories\InspectionlistReget;
use Modules\Intelligent\Models\Otherstorage;
use Modules\Intelligent\Models\Otherstorageschedule;
use Modules\Intelligent\Models\Lotbinding;
use App\Enums\BoxFrom;
use App\Services\InventoryService;
use App\Services\KingDeeService;
use App\Enums\InvTransDocType;
use Modules\Inventory\Models\Inventory;

class IntelligentReget
{


    /*
    数据列表
    */
    public static function list($data = [])
    {
        return self::getBuilder($data)->paginate($data['limit'] ?? 20);
    }


     /**
     *查询列表
     *
     * @param array $data
     * @return Builder
     */
    public static function getBuilder(array $data = []): Builder
    {
       
        $builder = Otherstorage::query();
        if (isset($data['othernumbers'])) {
            $builder->where('othernumbers', 'like', "%{$data['othernumbers']}%");
        }
        
        if (isset($data['remark'])) {
        $builder->where('remark', 'like', "%{$data['remark']}%");
        }
        
        if (isset($data['incomingtype'])) {
           
                $builder->where('incomingtype',$data['incomingtype']);
           
        }
        if (isset($data['state'])) {
           
                $builder->where('state',$data['state']);
           
        }
        if (isset($data['backstate'])) {
           
                $builder->where('backstate',$data['backstate']);
           
        }
        if (isset($data['incomingdate'])) {
            $builder->where('incomingdate','>=' , $data['incomingdate'][0].' 00:00:00');
            $builder->where('incomingdate','<=' ,  $data['incomingdate'][1].' 23:59:59');
        }
        
        
        $builder->orderBy('id', 'desc');

        return $builder;
    }


    

    /*
    数据添加方法
    */
    public static function create(array $data)
    {
        $Otherstorage = new Otherstorage;
        return self::createOrSave($Otherstorage, $data);
    }

    //数据添加方法
    public static function createOrSave(Otherstorage $Otherstorage,$data)
    {


        $Model = [];
        $kingDeeService = new warehouseService();
        $resdata = $kingDeeService->warehousedataApiTwo();

        try {
            //开始起事务
            DB::beginTransaction();

            $Otherstoragedata = [];
            // $Otherstoragedata['othernumbers']   = 'QTRK'.date('Ymd',time()).makeSerial(); 
            $Otherstoragedata['othernumbers']   = \App\Services\UnitService::createDocno(\App\Enums\OrderNoPrefix::NO_QTRK->value); 
            $Otherstoragedata['incomingtype']   = $data['incomingtype'];
            $Otherstoragedata['incomingdate']   = date('Y-m-d H:i:s',time());
            $Otherstoragedata['creator_id']   =  $data['creator_id'];//创建人
            $Otherstoragedata['remark']         = $data['remark'];
            $Otherstorage->fill($Otherstoragedata);
            $Otherstorage->save();

            $org = '';

            foreach($data['detailscheck_all'] as $k=>$v){

                if(empty($v['barcode'])){
                    throw new \Exception('箱号不能为空');
                }

                //库位
                $lcoation = Storagelocation::find($v['storagelocation']);
                if(!$lcoation){
                    throw new \Exception('库位代码不存在');
                }

                //仓库
                $wms = Stash::find($lcoation->owning_id);
                if(empty($org)){
                    $org = $wms->fuseorgid_number;
                }else{
                    if($org != $wms->fuseorgid_number){
                        throw new \Exception('同一提交仓库所属组织必须相同');
                    }
                }

                //产品
                $material = Material::find($v['material_id']);
                if(!$material){
                    throw new \Exception('品号不存在');
                }

                $detailscheckOne = [];
                $detailscheckOne['material_id']     = $v['material_id'];
                $detailscheckOne['storagelocation'] = $v['storagelocation'];
                $detailscheckOne['quantity']        = $v['quantity'];
                $detailscheckOne['barcode']         = $v['barcode'];
                $detailscheckOne['otherstorage_id'] = $Otherstorage['id'];
                $detailscheckOne['creator_id']      = UnitService::getUserId();
                $detailscheckOne['created_at']      = time();
                $detailscheckOne['updated_at']      = time();

                //保存入库明细
                $Otherstorage->detailscheckOne()->insert($detailscheckOne);

                /*$storagelocation = DB::table('storagelocation')
                ->select(
                    'storagelocation.warehousecode',
                    'storagelocation.owning_id',
                    'storagelocation.repositoryname',
                    'storagelocation.person',
                    'stash.fnumber',
                    'stash.fname',
                    'stash.fuseorgid_number',
                    )
                ->join('stash as stash', 'stash.id', '=', 'storagelocation.owning_id')
                ->where('storagelocation.id',$v['storagelocation'])
                ->first();

                // 判断是否绑定了箱号条码
                if($v['ifshow']==1){


                    $Bacode = BoxService::makeBoxNumber(
                        1,
                        BoxFrom::Other_WARE->value,
                        $Otherstorage['id'],
                        $storagelocation->fuseorgid_number,
                        $Otherstoragedata['othernumbers'],
                        $v['material_id'],
                    );
                    //$Bacode = BoxService::makeBoxNumber($data['modifier'],1,1);
                    $Bacodedata = [
                        'barcode'=>$Bacode[0],
                        'storagelocation'=>$v['storagelocation'],
                        'material_id'=>$v['material_id'],
                        'quantity'=>$v['quantity'],
                    ];
                    Lotbinding::insert($Bacodedata);

                    $detailscheckOne['barcode'] = $Bacode[0];
                }else{
                    $detailscheckOne['barcode'] = $v['barcode'];
                }*/


                //金蝶推送
                /*$inventory = DB::table('material')
                ->select('fnumber','fname','fspecification','funit_number','funit_name','fuseorgid_name','id','fbaseproperty_number','fbaseproperty_name')
                ->where('id',$v['material_id'])
                ->first();*/

                // $storagelocation = DB::table('storagelocation')
                // ->select('warehousecode','owning_id','repositoryname','person')
                // ->where('id',$v['storagelocation'])
                // ->first();

                // if(empty($inventory)||empty($storagelocation)){
                //     throw new FailedException('物料数据或者仓库数据出错');
                // }

                // $stash = DB::table('stash')
                // ->select('fmaterial','fnumber','fname','fuseorgid_number','fuseorgid_name')
                // ->where('id',$storagelocation->owning_id)->first();

                // $Model[$k]['FSRCBILLNO'] = $FBILLNO['warehosnumber'];//原单号采购入库单
                // $Model[$k]['FUNITID'] = $dataPurchaseorderschedule['funitid_number'];//单位（传编码）
                $Model[$k]['FSRCSEQ']       = '';//物料源单行号
                $Model[$k]['FMATERIALID']   = $material->fnumber; //SKU（传编码）
                $Model[$k]['FQTY']          = $v['quantity'];
                $Model[$k]['FGIVEAWAY']     = 'false';//是否赠品
                $Model[$k]['FOwnerTypeId']  = 'BD_OwnerOrg';//货主类型
                $Model[$k]['FOwnerId']      = $wms->fuseorgid_number;//货主编码
                $Model[$k]['FUNITID']       = $material->funit_number;//单位
                $Model[$k]['FSTOCKID']      = $wms->fnumber;
                // $Model[$k]['FORGID'] = $storagelocation->fuseorgid_number;//组织

                $addInvdata = [
                    'org_code'      => $wms->fuseorgid_number,
                    'cargo_code'    => $wms->fuseorgid_number,
                    'supplier_code' => $Otherstoragedata['othernumbers'],
                    'doc_id'        => $Otherstorage['id'],
                    'docno'         => $Otherstoragedata['othernumbers'],
                    'doc_type'      => InvTransDocType::OTHER_RECEIPT->value,
                    'material_no'   => $material->fnumber,//SKU
                    'location'      => $lcoation->warehousecode,
                    'qty'           => $v['quantity'],
                    'unit'          => $material->funit_number,
                    'lotnum'        => $detailscheckOne['barcode'],
                ];
                //添加库存
                $data = InventoryService::addInv($addInvdata);
            }

            $order = [
                'FID'=>0,
                'FBillNo'       =>$Otherstoragedata['othernumbers'],
                'FDATE'         =>date('Y-m-d H:i:s',time()),
                'FBILLTYPEID'   =>"STK_MISCELLANEOUS",
                'FORGID'        =>$wms->fuseorgid_number,//组织
                'FDESCRIPTION'  =>"QW001",//盘盈入库
                // 'FSRCBILLNO'=>'',
                'FEntity'       =>$Model,
            ];
            //金蝶推送
            (new KingDeeService())->form('TVJB_DJWMSDJ')->invokeSave($order);

            Otherstorage::where('id',$Otherstorage['id'])->update([
                'state'=>1,
                'backstate'=>1,
            ]);
            DB::commit();
            return '数据添加成功';
        } catch (\Exception $e) {
            DB::rollBack();
            throw $e;
        }

    }

    //修改
    public static function createUpdate($data)
    {

        try {
            //开始起事务
            DB::beginTransaction();
            $Inspectionlist = Inspectionlist::query()->updateOrCreate(['id' => $data['inspectionlist_id']], [
                'inspectiontime'       => time()  ?? '',
                'method'       => $data['method']  ?? '',
                'gitquantity'       => $data['gitquantity']  ?? '',
                'quantityincoming'       => $data['quantityincoming']  ?? '',
                'inspectionresult'       => $data['inspectionresult']  ?? '',
                'decision'       => $data['decision']  ?? 0,
                'inspector_user'       => $data['creator_id']  ?? '',
            ]);

            $Inspectionlist->detailscheckAll()->createMany($data['detailscheck_all']);

            DB::commit();
            return ['code'=>1000,'message'=>'检验成功'];
        } catch (\Exception $e) {
            DB::rollBack();
            throw new FailedException('服务器飞出地球了请联系技术找回');
        }

    }

    /**
     * 查询一条数据
     *
     */
    public static function find($id)
    {
        return Provisional::query()->with('detailscheckAll')->find($id);
    }

    /**
     * @param $id
     * @return void
     */
    public static function delete($id)
    {

        try {
            //开始起事务
            DB::beginTransaction();

            Otherstorage::query()->where('id',$id)->delete();
            Otherstorageschedule::query()->where('otherstorage_id',$id)->delete();
            DB::commit();
            return '删除成功';
        } catch (\Exception $e) {
            DB::rollBack();
           throw new FailedException('服务器飞出地球了请联系技术找回');
        }


    }
     /**修改接口
     * @param $id
     * @return void
     */
    public static function auditupdate($id,$data)
    {

        try {
            //开始起事务
            DB::beginTransaction();
            Otherstorageschedule::query()->updateOrCreate(['id' => $id], [
                'quantity' => $data['quantity'],
            ]);
            // $resdata = Provisionalschedule::select('id','provisional_id')->where('provisional_id',$id)->get();
            // foreach($resdata as $k=>$v){
            //     $Inspectionlist = [];
            //     $Inspectionlist['inspectionnumber'] = 'LLJY'.date('Ymd',time()).makeSerial();
            //     $Inspectionlist = Inspectionlist::insertGetId($Inspectionlist);
            //     Otherstorageschedule::query()->updateOrInsert(['id' => $v['id']], [
            //     'inspectionlist_id'=>$Inspectionlist,
            //     ]);
            //     Provisional::query()->updateOrCreate(['id' => $v['provisional_id']], [
            //         'state' => 1,
            //     ]);
            // }

            DB::commit();
            return ['code'=>1000,'message'=>'修改成功'];
        } catch (\Exception $e) {
            DB::rollBack();
            throw $e;
        }

    }


    /**
     * @param $id
     * @return void
     */
    public static function showApi($id)
    {
       $data = Otherstorage::select('othernumbers','incomingtype','incomingdate','state','state')
        ->where('id',$id)->first();
        foreach (Otherstorage::$Type as $k=>$v){
            $datatype[$v['value']] = $v['label'];
         }
         $data['incomingtype'] = isset($datatype[$data['incomingtype']])?$datatype[$data['incomingtype']]:"";

        if(empty($data)){
            throw new FailedException('数据出错');
        }else{

            $res = Otherstorageschedule::select('otherstorage_id','material_id','quantity','storagelocation','barcode')
            ->where('otherstorage_id',$id)
            ->get()
            ->toArray();

                foreach($res as $k=>$v){

                    $storagelocation = DB::table('storagelocation')
                    ->select('warehousecode','owning_id','repositoryname','person')
                    ->where('id',$v['storagelocation'])
                    ->first();

                    if(empty($storagelocation)){
                        throw new FailedException('仓库出错');
                    }

                    $res[$k]['warehousecode'] = $storagelocation->warehousecode;
                    $res[$k]['repositoryname'] = $storagelocation->repositoryname;

                    $stash = DB::table('stash')
                    ->select('fmaterial','fnumber','fname','fuseorgid_number','fuseorgid_name')
                    ->where('id',$storagelocation->owning_id)->first();

                    $res[$k]['fnumber_stash'] = $stash->fnumber;
                    $res[$k]['fname_stash'] = $stash->fname;

                    //盘点生成的入库单

                    if(empty($v['material_id'])){}

                    $material = DB::table('material')
                    ->select('fnumber','fname','fspecification','fspecification','funit_name','fuseorgid_name','fbaseproperty_number')
                    ->where('id',$v['material_id'])->first();

                    $res[$k]['fnumber'] = $material->fnumber;
                    $res[$k]['fname'] = $material->fname;
                    $res[$k]['fspecification'] = $material->fspecification;
                    $res[$k]['funit_name'] = $material->funit_name;
            }

            $data['detailscheck_all'] = $res;
            return ['code'=>1000,'message'=>'扫描成功','data'=>$data];

        }


    }
    /**
     * @param $id
     * @return void
     */
    public static function Barcodename($code)
    {

        $boxInfo = BoxNumberRepository::getBoxByCode($code);
        if(!$boxInfo){
            throw new \Exception('箱号不存在');
        }

        //先查库存
        $inventory = Inventory::select('org_code','material_no','location','unit','qty','lot_num','assign_qty','lock_qty')
        ->where('lot_num',$code)->get()
        ->toArray();
        if(!empty($inventory)){
                foreach($inventory as $k=>$v){
                    // 库位
                $storagelocation = DB::table('storagelocation')
                ->select('warehousecode','owning_id','repositoryname','person','id')
                ->where('warehousecode',$v['location'])
                ->first();
                // 仓库
                $stash = DB::table('stash')
                ->select('fmaterial','fnumber','fname','fuseorgid_number','fuseorgid_name')
                ->where('id',$storagelocation->owning_id)->first();
                
                $material = DB::table('material')
                ->select('fname','fnumber','fspecification','id')
                ->where('fnumber',$v['material_no'])
                ->first();
                
                $inventory[$k]['material_id'] = $material->id;
                $inventory[$k]['material_name'] = $material->fname;
                $inventory[$k]['storagelocation'] =  $storagelocation->id;
                $inventory[$k]['fnumber'] =  $stash->fnumber;
                $inventory[$k]['fname'] =  $stash->fname;
                $inventory[$k]['qty'] =  $v['qty']-$v['assign_qty']-$v['lock_qty'];
            }
        }
       
        
            // if(empty($inventory)){
            //         $data = [];
            //         $inventory = DB::table('material')
            //         ->select('fnumber','fname','fspecification','funit_number','funit_name','fuseorgid_name','id','fbaseproperty_number','fbaseproperty_name')
            //         ->where('fnumber',$inventory->material_no)
            //         ->where('funit_number',$inventory->unit)
            //         ->first();
            //         if(empty($inventory)){
            //             throw new FailedException('物料获取失败，请联系技术处理。');
            //         }
            // }

            return $inventory;
            //return ['code'=>1000,'message'=>'扫描成功','data'=>$inventory];
            //  先库存的编码
            // $Purchaseorder = Purchaseorder::select('id','fpurchaseorgid_number')->where('fpurchaseorgid_number',$inventory->org_code)->first();
            // $Purchaseorderschedule = Purchaseorderschedule::select('fmaterialid','fmaterialname','fmaterialmodel','funitid_number','funitid_name')
            // ->where('purchaseorder_id',$Purchaseorder->id)
            // ->where('fmaterialid',$inventory->material_no)
            // ->where('funitid_number',$inventory->unit)
            // ->first();

            // $data['fmaterialid'] = $Purchaseorderschedule->fmaterialid;
            // $data['funitid_number'] = $Purchaseorderschedule->funitid_number;
            // $data['funitid_name'] = $Purchaseorderschedule->funitid_name;
            // $data['purchaseorderschedule_id'] = $Purchaseorderschedule->id;

        
            // $data['warehousecode'] = $storagelocation->warehousecode;
            // $data['repositoryname'] = $storagelocation->repositoryname;
            // $data['fname'] = $stash->fname;


            // $data['Otherquantity'] = '';



    }



    /*审核接口
     * @param $id
     * @return void
     */
    public static function checkPdaApi($id)
    {

        $Otherstorage = Otherstorage::query()
        ->select('id','othernumbers')
        ->where('id',$id)
        ->first()
        ->toArray();

        $Otherstorageschedule = Otherstorageschedule::query()
        ->select('otherstorage_id','material_id','storagelocation','barcode',DB::raw('SUM(quantity) as quantity'),)
        ->where('otherstorage_id',$id)
        ->groupby(['otherstorage_id','material_id','quantity','storagelocation','barcode'])
        ->get()
        ->toArray();

        if(empty($Otherstorage)||empty($Otherstorageschedule)){
            throw new FailedException('数据出错,无法获取数据');
        }

        $Model = [];
        $kingDeeService = new warehouseService();
        $resdata = $kingDeeService->warehousedataApiTwo();

        try {
            //开始起事务
            DB::beginTransaction();

            foreach($Otherstorageschedule as $k=>$v){

                $inventory = DB::table('material')
                ->select('fnumber','fname','fspecification','funit_number','funit_name','fuseorgid_name','id','fbaseproperty_number','fbaseproperty_name')
                ->where('id',$v['material_id'])
                ->first();

                $storagelocation = DB::table('storagelocation')
                ->select('warehousecode','owning_id','repositoryname','person')
                ->where('id',$v['storagelocation'])
                ->first();

                if(empty($inventory)||empty($storagelocation)){
                    throw new FailedException('物料数据或者仓库数据出错');
                }

                $stash = DB::table('stash')
                ->select('fmaterial','fnumber','fname','fuseorgid_number','fuseorgid_name')
                ->where('id',$storagelocation->owning_id)->first();

                // $Model[$k]['FSRCBILLNO'] = $FBILLNO['warehosnumber'];//原单号采购入库单
                $Model[$k]['FSRCSEQ'] = '';//物料源单行号
                $Model[$k]['FMATERIALID'] = $inventory->fnumber; //SKU（传编码）
                // $Model[$k]['FUNITID'] = $dataPurchaseorderschedule['funitid_number'];//单位（传编码）
                $Model[$k]['FQTY'] = $v['quantity'];
                $Model[$k]['FGIVEAWAY'] = 'false';//是否赠品

                if(isset($resdata[$storagelocation->owning_id])){
                    $Model[$k]['FSTOCKID']= $resdata[$storagelocation->owning_id]['FNumber'];
                }else{
                return throw new FailedException('库位出错');
                }

                $datares = DB::table('inventory')
                ->select('id','qty')
                ->where('org_code',$stash->fuseorgid_number)//使用组织
                ->where('location',$resdata[$storagelocation->owning_id]['FNumber'])//仓库编码
                ->where('material_no',$inventory->fnumber)//SKU
                ->where('unit',$inventory->funit_number)//单位编码
                ->where('lot_num',$v['barcode'])//批号
                ->first();

                // if(!empty($datares)){
                //     $quantity = $datares->qty + $v['quantity'];
                //     $id = DB::table('inventory')->where('id',$datares->id)->update(['qty'=>$quantity]);
                // }// else{

                //     $inventorydata = [];
                //     $inventorydata['lot_num'] = $stash->fuseorgid_number;
                //     $inventorydata['org_code'] = $v['barcode'];
                //     $inventorydata['material_no'] = $inventory->fnumber;
                //     $inventorydata['unit'] = $inventory->funit_number;
                //     $inventorydata['location'] = $resdata[$storagelocation->owning_id]['FNumber'];
                //     $inventorydata['qty'] = $v['quantity'];

                //     //更新及时库存
                //     DB::table('inventory')->insertGetId($inventorydata);
                // }

                //更新库存临时表
                // $inventory_trans = [
                //     'org_code'=>$stash->fuseorgid_number,
                //     'doc_id'=>$id,
                //     'docno'=>$Otherstorage['othernumbers'],
                //     'doc_type'=>60,
                //     'trans_type'=>10,
                //     'material_no'=>$inventory->fnumber,//SKU
                //     'from_location'=>$resdata[$storagelocation->owning_id]['FNumber'],
                //     'from_lotnum'=>$v['barcode'],
                //     'from_unit'=>$inventory->funit_number,
                //     'qty'=>$v['quantity'],
                //     'to_location'=>$resdata[$storagelocation->owning_id]['FNumber'],
                //     'to_lotnum'=>$v['barcode'],
                //     'to_unit'=>$inventory->funit_number,
                // ];
                // //变动库存
                // DB::table('inventory_trans')->insert($inventory_trans);

                $inventory = [
                        'org_code'=>$stash->fuseorgid_number,
                        'doc_id'=>$id,
                        'docno'=>$Otherstorage['othernumbers'],
                        'doc_type'=>60,
                        'material_no'=>$inventory->fnumber,//SKU
                        'location'=>$resdata[$storagelocation->owning_id]['FNumber'],
                        'qty'=>$v['quantity'],
                        'unit'=>$inventory->funit_number,
                        'lotnum'=>$v['barcode'],
                    ];

                $data = InventoryService::addInv($inventory);
            }


            $order = [
                'FID'=>0,
                'FBillNo'=>$Otherstorage['othernumbers'],
                'FDATE'=>date('Y-m-d H:i:s',time()),
                'FBILLTYPEID'=>"STK_MISCELLANEOUS",
                'FDESCRIPTION'=>"QW001",//盘盈入库
                'FSRCBILLNO'=>'',
                'FEntity'=>$Model,
            ];
            //金蝶推送
            (new KingDeeService())->form('TVJB_DJWMSDJ')->invokeSave($order);

            return ['code'=>1000,'message'=>'审核成功'];
            DB::commit();
            return '扫描成功';
        } catch (\Exception $e) {
            DB::rollBack();
            throw new FailedException('服务器飞出地球了请联系技术找回');
        }

    }




}
